package com.gddb.xwj.mywiki.service;

import com.gddb.xwj.mywiki.domain.Ebook;
import com.gddb.xwj.mywiki.domain.EbookExample;
import com.gddb.xwj.mywiki.mapper.EbookMapper;
import com.gddb.xwj.mywiki.req.EbookQueryReq;
import com.gddb.xwj.mywiki.req.EbookSaveReq;
import com.gddb.xwj.mywiki.resp.EbookQueryResp;
import com.gddb.xwj.mywiki.resp.PageResp;
import com.gddb.xwj.mywiki.util.CopyUtil;
import com.gddb.xwj.mywiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 描述：电子书
 *
 * @author xwj
 * @create 2022-03-19 17:53
 */
@Service
@Slf4j
public class EbookService {

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req){
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }
        //只会对第一个遇到的select生效
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);
        // 列表复制
        List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        //注意点 PageInfo<EbookQueryResp> pageInfo = new PageInfo<>(list); 如果pageinfo用的是EbookQueryResp 则返回的是分页的总数 必须为ebook才是全部
        log.info("总行数 :{}", pageInfo.getTotal());
        log.info("总页数 :{}", pageInfo.getPages());

        PageResp<EbookQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     * @param req
     */
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if(ObjectUtils.isEmpty(req.getId())){
            //新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        }else{
            //修改
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
